package com.jmb.waimao.service.impl;

import com.jmb.waimao.entity.EmailAddress;
import com.jmb.waimao.service.EmailSendingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * Implementation of EmailSendingService
 */
@Service
@Slf4j
public class EmailSendingServiceImpl implements EmailSendingService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username:user@localhost}")
    private String fromEmail;

    @Override
    public boolean sendEmail(String to, String subject, String content) {
        try {
            log.info("Preparing to send email to: {}", to);
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // true indicates HTML content

            log.info("Sending email to: {} with subject: {}", to, subject);
            mailSender.send(message);
            log.info("Email sent successfully to: {}", to);
            return true;
        } catch (MessagingException e) {
            log.error("Failed to send email to {} due to messaging exception: {}", to, e.getMessage(), e);
            return false;
        } catch (Exception e) {
            log.error("Unexpected error sending email to {}: {}", to, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean sendEmail(EmailAddress recipient, String subject, String content) {
        String personalizedContent = content;

        // Personalize content if recipient name is available
        if (recipient.getName() != null && !recipient.getName().isEmpty()) {
            personalizedContent = personalizedContent.replace("{name}", recipient.getName());
        } else {
            personalizedContent = personalizedContent.replace("{name}", "");
        }

        return sendEmail(recipient.getEmail(), subject, personalizedContent);
    }
}
